package com.study.talk.ui.app.launcher

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.study.talk.R
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.ui.app.login.LoginActivity
import com.study.talk.netty.NettyService
import com.study.common.event.Constants
import com.study.common.event.OtherMessage
import com.study.talk.utils.alert.AlertUtil
import com.study.talk.utils.alert.CustomDialog
import com.study.talk.utils.extras.start
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe


class StartActivity : BaseActivity() {

    val dialog : CustomDialog by lazy { AlertUtil.showCustomDialog(
        this@StartActivity, "网络错误", "服务器连接失败"
    ) {  finish() } }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start)
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        run {
            val channelId = "畅聊好友消息" //通知渠道的标识符
            val channelName = "好友消息通知"
            val channelDescription = "来自好友的消息"
            val notificationChannel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.description = channelDescription
            manager.createNotificationChannel(notificationChannel)
        }

        run {
            val channelId = "畅聊群聊消息" //通知渠道的标识符
            val channelName = "群聊消息通知"
            val channelDescription = "来自群聊的消息"
            val notificationChannel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.description = channelDescription
            manager.createNotificationChannel(notificationChannel)
        }
        startForegroundService(Intent(this@StartActivity, NettyService::class.java))
    }

    @Subscribe
    fun onMessage(message: OtherMessage) {
        when (message.event) {
            Constants.CONNECTION_ERROR -> {
                lifecycleScope.launch(Dispatchers.Main) {
                    if (dialog.isShowing){
                        dialog.dismiss()
                    }
                    dialog.show()
                }
            }

            Constants.CONNECTION_SUCCESS -> {
                start(LoginActivity::class.java)
                finish()
            }
        }
    }
}